<template>
  <div class="projects-container">
    <div class="projects-header">
      <h3>项目管理</h3>
      <el-button type="primary" @click="showAddProjectDialog">添加项目</el-button>
    </div>

    <div class="empty-tip" v-if="projects.length === 0">暂无项目，请添加</div>

    <el-card v-for="project in projects" :key="project.id" class="project-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="project-title">{{ project.name }}</span>
          <div class="header-actions">
            <el-button text type="primary" @click="showEditProjectDialog(project)">编辑</el-button>
            <el-button text type="danger" @click="confirmDeleteProject(project)">删除</el-button>
          </div>
        </div>
      </template>

      <div class="project-desc">{{ project.description }}</div>

      <div class="project-details">
        <div class="detail-item">
          <span class="label">起止时间:</span>
          <span>{{ project.startDate }} 至 {{ project.endDate }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">总负责人:</span>
          <div class="user-info">
            <el-avatar :size="small" :src="project.leader.avatar"></el-avatar>
            <span>{{ project.leader.name }}</span>
          </div>
        </div>
        
        <div class="detail-item">
          <span class="label">项目进度:</span>
          <div class="progress-info">
            <el-progress :percentage="project.progress" :color="progressColor"></el-progress>
          </div>
        </div>
      </div>

      <div class="modules-section">
        <div class="section-header">
          <h4>项目模块</h4>
          <el-button size="small" type="primary" plain @click="showAddModuleDialog(project)">添加模块</el-button>
        </div>

        <div class="modules-list">
          <el-empty v-if="project.modules.length === 0" description="暂无项目模块"></el-empty>
          
          <el-card v-for="module in project.modules" :key="module.id" class="module-card" shadow="never">
            <div class="module-content">
              <div class="module-info">
                <h5>{{ module.name }}</h5>
                <div class="module-leader">
                  <span class="label">负责人:</span>
                  <div class="user-info">
                    <el-avatar :size="small" :src="module.leader.avatar"></el-avatar>
                    <span>{{ module.leader.name }}</span>
                  </div>
                </div>
              </div>
              
              <div class="module-actions">
                <el-button size="small" text @click="showEditModuleDialog(project, module)">编辑</el-button>
                <el-button size="small" text type="danger" @click="confirmDeleteModule(project, module)">删除</el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>

    <!-- 项目对话框 -->
    <el-dialog
      v-model="projectDialogVisible"
      :title="isEdit ? '编辑项目' : '添加项目'"
      width="50%"
    >
      <el-form :model="projectForm" label-width="120px">
        <el-form-item label="项目名称" required>
          <el-input v-model="projectForm.name" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        
        <el-form-item label="项目描述">
          <el-input v-model="projectForm.description" type="textarea" placeholder="请输入项目描述"></el-input>
        </el-form-item>
        
        <el-form-item label="项目负责人" required>
          <el-select v-model="projectForm.leader" placeholder="请选择项目负责人">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user">
              <div class="user-option">
                <el-avatar :size="small" :src="user.avatar"></el-avatar>
                <span>{{ user.name }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="起止时间" required>
          <el-date-picker
            v-model="projectDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="projectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveProject">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 模块对话框 -->
    <el-dialog
      v-model="moduleDialogVisible"
      :title="isEdit ? '编辑模块' : '添加模块'"
      width="50%"
    >
      <el-form :model="moduleForm" label-width="120px">
        <el-form-item label="模块名称" required>
          <el-input v-model="moduleForm.name" placeholder="请输入模块名称"></el-input>
        </el-form-item>
        
        <el-form-item label="模块负责人" required>
          <el-select v-model="moduleForm.leader" placeholder="请选择模块负责人">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user">
              <div class="user-option">
                <el-avatar :size="small" :src="user.avatar"></el-avatar>
                <span>{{ user.name }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="moduleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveModule">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 数据部分
const projects = ref([
  {
    id: 1,
    name: '生活轨迹系统开发',
    description: '开发一个记录用户日常生活轨迹的应用',
    leader: {
      id: 1,
      name: '张三',
      avatar: '/src/assets/avatar.png'
    },
    progress: 65,
    startDate: '2024-01-15',
    endDate: '2024-06-30',
    modules: [
      {
        id: 1,
        name: '前端开发',
        leader: {
          id: 2,
          name: '李四',
          avatar: '/src/assets/avatar.png'
        }
      },
      {
        id: 2,
        name: '后端开发',
        leader: {
          id: 3,
          name: '王五',
          avatar: '/src/assets/avatar.png'
        }
      }
    ]
  },
  {
    id: 2,
    name: '数据分析平台',
    description: '构建企业内部数据分析和可视化平台',
    leader: {
      id: 4,
      name: '赵六',
      avatar: '/src/assets/avatar.png'
    },
    progress: 30,
    startDate: '2024-03-01',
    endDate: '2024-08-15',
    modules: [
      {
        id: 1,
        name: '数据采集',
        leader: {
          id: 5,
          name: '钱七',
          avatar: '/src/assets/avatar.png'
        }
      }
    ]
  }
])

const userList = ref([
  { id: 1, name: '张三', avatar: '/src/assets/avatar.png' },
  { id: 2, name: '李四', avatar: '/src/assets/avatar.png' },
  { id: 3, name: '王五', avatar: '/src/assets/avatar.png' },
  { id: 4, name: '赵六', avatar: '/src/assets/avatar.png' },
  { id: 5, name: '钱七', avatar: '/src/assets/avatar.png' },
  { id: 6, name: '孙八', avatar: '/src/assets/avatar.png' }
])

// 对话框状态
const projectDialogVisible = ref(false)
const moduleDialogVisible = ref(false)
const isEdit = ref(false)
const currentProjectId = ref(null)
const currentModuleId = ref(null)

// 表单对象
const projectForm = ref({
  name: '',
  description: '',
  leader: null
})
const projectDateRange = ref([])

const moduleForm = ref({
  name: '',
  leader: null
})

// 颜色计算
const progressColor = (percentage) => {
  if (percentage < 30) return '#909399'
  if (percentage < 70) return '#1e5eff'
  return '#67c23a'
}

// 显示添加项目对话框
function showAddProjectDialog() {
  isEdit.value = false
  projectForm.value = {
    name: '',
    description: '',
    leader: null
  }
  projectDateRange.value = []
  projectDialogVisible.value = true
}

// 显示编辑项目对话框
function showEditProjectDialog(project) {
  isEdit.value = true
  currentProjectId.value = project.id
  projectForm.value = {
    name: project.name,
    description: project.description,
    leader: project.leader
  }
  projectDateRange.value = [project.startDate, project.endDate]
  projectDialogVisible.value = true
}

// 保存项目
function saveProject() {
  // 验证表单
  if (!projectForm.value.name) {
    ElMessage.warning('请输入项目名称')
    return
  }
  
  if (!projectForm.value.leader) {
    ElMessage.warning('请选择项目负责人')
    return
  }
  
  if (!projectDateRange.value || projectDateRange.value.length < 2) {
    ElMessage.warning('请选择项目起止时间')
    return
  }
  
  if (isEdit.value) {
    // 编辑现有项目
    const index = projects.value.findIndex(p => p.id === currentProjectId.value)
    if (index !== -1) {
      projects.value[index] = {
        ...projects.value[index],
        name: projectForm.value.name,
        description: projectForm.value.description,
        leader: projectForm.value.leader,
        startDate: projectDateRange.value[0],
        endDate: projectDateRange.value[1]
      }
      ElMessage.success('项目更新成功')
    }
  } else {
    // 添加新项目
    const newId = Math.max(0, ...projects.value.map(p => p.id)) + 1
    projects.value.push({
      id: newId,
      name: projectForm.value.name,
      description: projectForm.value.description,
      leader: projectForm.value.leader,
      progress: 0,
      startDate: projectDateRange.value[0],
      endDate: projectDateRange.value[1],
      modules: []
    })
    ElMessage.success('项目添加成功')
  }
  
  projectDialogVisible.value = false
}

// 确认删除项目
function confirmDeleteProject(project) {
  ElMessageBox.confirm(
    '确定要删除这个项目吗？此操作不可恢复。',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    projects.value = projects.value.filter(p => p.id !== project.id)
    ElMessage.success('项目已删除')
  }).catch(() => {
    // 取消删除，不做任何操作
  })
}

// 显示添加模块对话框
function showAddModuleDialog(project) {
  isEdit.value = false
  currentProjectId.value = project.id
  moduleForm.value = {
    name: '',
    leader: null
  }
  moduleDialogVisible.value = true
}

// 显示编辑模块对话框
function showEditModuleDialog(project, module) {
  isEdit.value = true
  currentProjectId.value = project.id
  currentModuleId.value = module.id
  moduleForm.value = {
    name: module.name,
    leader: module.leader
  }
  moduleDialogVisible.value = true
}

// 保存模块
function saveModule() {
  // 验证表单
  if (!moduleForm.value.name) {
    ElMessage.warning('请输入模块名称')
    return
  }
  
  if (!moduleForm.value.leader) {
    ElMessage.warning('请选择模块负责人')
    return
  }
  
  const projectIndex = projects.value.findIndex(p => p.id === currentProjectId.value)
  if (projectIndex === -1) return
  
  if (isEdit.value) {
    // 编辑现有模块
    const moduleIndex = projects.value[projectIndex].modules.findIndex(m => m.id === currentModuleId.value)
    if (moduleIndex !== -1) {
      projects.value[projectIndex].modules[moduleIndex] = {
        ...projects.value[projectIndex].modules[moduleIndex],
        name: moduleForm.value.name,
        leader: moduleForm.value.leader
      }
      ElMessage.success('模块更新成功')
    }
  } else {
    // 添加新模块
    const newId = Math.max(0, ...projects.value[projectIndex].modules.map(m => m.id)) + 1
    projects.value[projectIndex].modules.push({
      id: newId,
      name: moduleForm.value.name,
      leader: moduleForm.value.leader
    })
    ElMessage.success('模块添加成功')
  }
  
  moduleDialogVisible.value = false
}

// 确认删除模块
function confirmDeleteModule(project, module) {
  ElMessageBox.confirm(
    '确定要删除这个模块吗？此操作不可恢复。',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const projectIndex = projects.value.findIndex(p => p.id === project.id)
    if (projectIndex !== -1) {
      projects.value[projectIndex].modules = projects.value[projectIndex].modules.filter(m => m.id !== module.id)
      ElMessage.success('模块已删除')
    }
  }).catch(() => {
    // 取消删除，不做任何操作
  })
}
</script>

<style scoped>
.projects-container {
  padding: 20px;
}

.projects-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.projects-header h3 {
  margin: 0;
  font-size: 24px;
  color: #1e5eff;
}

.project-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  animation: cardFadeIn 0.5s ease forwards;
  opacity: 0;
  transform: translateY(20px);
}

.project-card:nth-child(2) { animation-delay: 0.1s; }
.project-card:nth-child(3) { animation-delay: 0.2s; }
.project-card:nth-child(4) { animation-delay: 0.3s; }

@keyframes cardFadeIn {
  to { opacity: 1; transform: translateY(0); }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.project-title {
  font-size: 18px;
  font-weight: bold;
  color: #1e5eff;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.project-desc {
  color: #606266;
  margin-bottom: 20px;
  line-height: 1.5;
}

.project-details {
  background-color: #f9fbff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  color: #909399;
  margin-right: 10px;
  min-width: 80px;
}

.user-info, .user-option {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-info {
  flex: 1;
}

.modules-section {
  margin-top: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  color: #1e5eff;
}

.modules-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.module-card {
  border: 1px solid #ebeef5;
  border-left: 4px solid #1e5eff;
}

.module-content {
  display: flex;
  justify-content: space-between;
}

.module-info h5 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 15px;
  color: #303133;
}

.module-leader {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.module-actions {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.empty-tip {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

:deep(.el-button--primary) {
  background-color: #1e5eff;
}

:deep(.el-date-editor) {
  width: 100%;
}
</style> 